<?php


namespace App\Http\Controllers\Index;


use App\Http\Controllers\Controller;
use App\Model\Product;
use App\Model\UserCollection;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    protected $param;
    public function __construct(Request $request)
    {
        if ($request->isMethod('GET')){
            $this->param = json_decode($request->input('params'),true);
        }elseif ($request->isMethod('POST')){
            $this->param = $request->input('params');
        }
    }

    public function product_list(){
        $products = Product::where(['status' => 1,'command_type' => 'hot'])->get();
        return JsonResponse(200,true,'获取成功',$products);
    }

    public function detail(){
        $detail = Product::with('banner')
            ->with('comment')
            ->where('id',$this->param['id'])
            ->first();
        $detail->banner = getImageUrl($detail->banner,'url');
        if ($detail){
            return JsonResponse(200,true,'获取成功',$detail);
        }else{
            return JsonResponse(4000,false,'获取失败');
        }
    }

    public function collection(Request $request){
        $user_collection = new UserCollection;
        $user_collection->product_id = $request->post('product_id');
        $user_collection->user_id = $request->post('user_id');
        if ($user_collection->save()){
            return JsonResponse(200,true,'收藏成功');
        }else{
            return JsonResponse(4001,false,'收藏失败');
        }
    }

    public function keyword_search(Request $request){
        $category_id = $request->post('category_id');
        $page = $request->post('page');
        $list = Product::where('category_id',$category_id)
            ->orderBy('id','DESC')
            ->paginate(10,'*',2,$page);;
        return JsonResponse(200,true,'获取成功',$list);
    }
}
